package com.work.lxykeeper.httpretrofit;

/**
 * author：WangZhan
 * data: 2016/12/6 11:47
 * version: 1.0.0
 * explain:网络访问辅助类
 */

import android.content.Context;
import android.net.ConnectivityManager;

import com.work.lxykeeper.utils.LogUtils;
import com.work.lxykeeper.utils.SignStrUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;


public class RetrofitManager {

    private static OkHttpClient client;
    private static com.work.lxykeeper.httpretrofit.RetrofitManager RetrofitManager;
    private static RetrofitApi retrofitInterface;

    private RetrofitManager() {
        getLogIntercepter();
        initRetrofit();
    }


    public static RetrofitApi getInstance() {
        if (RetrofitManager == null) {
            RetrofitManager = new RetrofitManager();
        }
        return retrofitInterface;
    }

    private void initRetrofit() {
        client = new OkHttpClient.Builder()
                .addNetworkInterceptor(getHeaderIntercepter())
                .addInterceptor(getLogIntercepter())
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(1000, TimeUnit.MINUTES)
                .writeTimeout(1000, TimeUnit.MINUTES).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Url.URL)//域名
                //增加返回值为String的支持
//                .addConverterFactory(ScalarsConverterFactory.create())
//                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(CustomGsonConverterFactory.create())
                .client(client)//如果对每个请求都需要添加特定的heads，可以这样来配置
                .build();
        retrofitInterface = retrofit.create(RetrofitApi.class);
    }

    /**
     * 检测网络是否连接
     *
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        // 得到网络连接信息
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // 去进行判断网络是否连接
        if (manager.getActiveNetworkInfo() != null) {
            return manager.getActiveNetworkInfo().isAvailable();
        }
        return false;
    }

    /**
     * 日志拦截器
     */
    private HttpLoggingInterceptor getLogIntercepter() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                LogUtils.i("RetrofitLog", "retrofitBack = " + message);
            }
        });
        //类型为BASIC，其实日志级别分为4类：NONE、BASIC、HEADERS、BODY。
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        return loggingInterceptor;
    }

    /**
     * 网络拦截器可添加header
     */
    private Interceptor getHeaderIntercepter() {
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request request = original.newBuilder()
                        .header("sign", SignStrUtil.getSign())
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            }
        };
        return interceptor;
    }
}
